import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "" //自动生成
packageNamePO = "com.yunji.it.hrm.dal.po"
authorName = "yinzn"
FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def className = javaName(table.getName(), true)
    def varName = javaName(table.getName(), false)
    packageName = getPackageName(dir)
    new File(dir, className + "Mapper.java").withPrintWriter { out -> generateInterface(out, className, varName) }
}

/**
 * 获取包名称
 * @param dir 实体类所在目录
 * @return
 */
def getPackageName(dir) {
    return dir.toString().replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generateInterface(out, baseName, varName) {
    out.println "package $packageName"
    def date = new Date().format("yyyy/MM/dd")
    def packageNamePO = packageName.replaceAll("\\.mapper;", ".po")
    out.println ""
    out.println "import ${packageNamePO}.${baseName}PO;"
    out.println ""
    out.println "import java.util.List;"
    out.println ""
    out.println "import org.springframework.stereotype.Repository;"
    out.println ""
    out.println "/**"
    out.println " * "
    out.println " * @author $authorName"
    out.println " * @version V1.0"
    out.println " * @since $date"
    out.println " */"
    out.println "@Repository"
    out.println "public interface ${baseName}Mapper{" // 可自定义
    out.println ""
    out.println "    ${baseName}PO get(long id);"
    out.println "    void insert(${baseName}PO ${varName}PO);"
    out.println "    void delete(long id);"
    out.println "    void update(${baseName}PO ${varName}PO);"
    out.println "    List<${baseName}PO> select(${baseName}PO param);"
    out.println ""
    out.println "}"
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    name = capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}